package com.lhs.controller;

import com.google.common.base.Strings;
import com.lhs.exception.WxException;
import com.lhs.exception.WxRuntimeException;
import com.lhs.utils.PropertyUtil;
import com.lhs.utils.WxUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * WeixinController
 *
 * @author longhuashen
 * @since 15/12/6
 */
@Controller
@RequestMapping("/weixin")
public class WeixinController {

    public static PropertyUtil propertyUtil = PropertyUtil.getInstance("config");

    private static final Logger logger = LoggerFactory.getLogger(WeixinController.class);

    @RequestMapping(value = {"", "/"}, method = RequestMethod.GET)
    @ResponseBody
    public String index(HttpServletRequest request) {
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");

        try {
            echostr = WxUtil.checkSignature(propertyUtil.getProperty("token"), signature, timestamp, nonce, echostr);
            if (!Strings.isNullOrEmpty(echostr)) {
                return echostr;
            } else {
                return "";
            }
        } catch (WxException e) {
            logger.error("接入微信失败!", e);
            throw new WxRuntimeException("接入微信失败!");
        }
    }
}
